//
//  AdventureDetailVController.m
//  Food
//
//  Created by dlios on 15-7-15.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "AdventureDetailVController.h"
#import "AdventureDetail_CollectionViewCell.h"
#import "Adventure_Detail_Lable_Cell.h"
#import "AdventureDetailModel.h"
#import "AFNetworkHandler.h"
#import "UIImageView+WebCache.h"
#import "Adventure_Detail_Header_View.h"
#import "AdventureDetail_Recommend_Model.h"
#import "AdventureDetail_Recommend_Header_View.h"
#import "HomePage_display_Controller.h"
#import "AdventureModel.h"
#import "SQL_DataBase.h"
#import "BaseHeader.h"
#import "GetHeight.h"
#import <ShareSDK/ShareSDK.h>

@interface AdventureDetailVController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIAlertViewDelegate>
@property (nonatomic, retain) UICollectionView *recommendView;
@property (nonatomic, assign) float height;
@property (nonatomic, retain) UIButton *openButton;
@end

@implementation AdventureDetailVController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     self.height = 135 / 320.0 *ScreenWidth ;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"naviBack"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    self.navigationItem.title = self.string;
    [self getAdventureDetailData];
    NSLog(@"5s:%f", self.view.frame.size.width);
}

- (void) back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.translucent = NO;
}

- (void)getAdventureDetailData
{
    UIActivityIndicatorView *activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
    
    activityIndicator.frame = CGRectMake(0, 0, 100, 100);
    
    activityIndicator.color = [UIColor grayColor];
    
    activityIndicator.center = CGPointMake(ScreenWidth / 2.0, ScreenHeight / 2.0 - 50);
    
    [self.view addSubview:activityIndicator];
    
    [activityIndicator startAnimating];
    NSString *str = [NSString stringWithFormat:@"http://121.41.88.179:80/HandheldKitchen/api/found/tblFresh!getTblFreshDelicacyList.do?freshId=%@&is_traditional=0&phonetype=1", self.freshid];
    [AFNetworkHandler getWithAFNByURL:str completion:^(id result) {
        NSArray *tempArr = [result objectForKey:@"data"];
        self.detailArray = [AdventureDetailModel arrayWithModelByArray:tempArr];
        [self createCollectionRecommendView];
        NSDictionary *recommendDic = tempArr[0];
        NSArray *recommendArry = recommendDic[@"vegetable"];
        self.recommendArray = [AdventureDetail_Recommend_Model arrayWithModelByArray:recommendArry];
        [self.recommendView reloadData];
        [activityIndicator stopAnimating];
    }];
}


- (void)createCollectionRecommendView
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

    layout.minimumInteritemSpacing = 2;
    layout.minimumLineSpacing = 20;
    layout.sectionInset = UIEdgeInsetsMake(10, 0, 10, 0);
    
    self.recommendView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64 - 49) collectionViewLayout:layout];
    self.recommendView.backgroundColor = [UIColor whiteColor];
    self.recommendView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backGround.jpg"]];
    self.recommendView.delegate = self;
    self.recommendView.dataSource = self;
    [self.view addSubview:self.recommendView];
    [self.recommendView release];
    [layout release];
    
    self.recommendView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    UIView *shareView = [[UIView alloc] initWithFrame:CGRectMake(0, 160.0 / 375 * ScreenWidth, ScreenWidth - 20 , 40.0 / 375 *ScreenWidth)];
    UIImageView *backGroundimage = [[UIImageView alloc] initWithFrame:shareView.bounds];
    backGroundimage.image = [UIImage imageNamed:@"收藏和分享5"];
    [shareView addSubview:backGroundimage];
    
    //shareView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"收藏和分享5"]];
    [self.recommendView addSubview:shareView];
    [shareView release];
    
    UIButton *collectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    collectButton.frame = CGRectMake(80.0 / 375 *ScreenWidth, 0, 50, 40.0 / 375 *ScreenWidth);
    [collectButton setTitle:@"收藏" forState:UIControlStateNormal];
    [collectButton setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    
    SQL_DataBase *dbManager = [SQL_DataBase shareInstance];
    [dbManager openDB];
    [dbManager creatTable2];
    AdventureModel *adventureModel = [dbManager selectActivityID:self.freshid];
    if ([adventureModel.freshId compare:@""])
    {
        collectButton.selected = YES;
    }
    [collectButton addTarget:self action:@selector(collection:) forControlEvents:UIControlEventTouchUpInside];
    [shareView addSubview:collectButton];
    
    
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    shareButton.frame = CGRectMake(shareView.frame.size.width / 2.0 + collectButton.frame.origin.x, collectButton.frame.origin.y, 50, 40.0 / 375 *ScreenWidth);
    [shareButton setTitle:@"分享" forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [shareView addSubview:shareButton];
    
    self.openButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.openButton.frame = CGRectMake(305.0 / 375 *ScreenWidth, 180 / 375.0 * ScreenWidth + self.height, 45, 20);
    self.openButton.backgroundColor = [UIColor orangeColor];
    self.openButton.layer.cornerRadius = 5;
    [self.openButton setTitle:@"展开" forState:UIControlStateNormal];
    [self.openButton setTitle:@"收起" forState:UIControlStateSelected];
    [self.openButton addTarget:self action:@selector(change:) forControlEvents:UIControlEventTouchUpInside];
    [self.recommendView addSubview:self.openButton];
    
    
    [self.recommendView registerClass:[AdventureDetail_CollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    [self.recommendView registerClass:[Adventure_Detail_Lable_Cell class] forCellWithReuseIdentifier:@"label"];
    
    [self.recommendView registerClass:[Adventure_Detail_Header_View class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    [self.recommendView registerClass:[AdventureDetail_Recommend_Header_View class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Recommend_Header"];
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        if (indexPath.section == 0) {
            Adventure_Detail_Header_View *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
            AdventureDetailModel *model = self.detailArray[0];
            [header.imageView sd_setImageWithURL:[NSURL URLWithString:model.imageFilename]];
            return header;
        }
        if (indexPath.section == 1) {
            AdventureDetail_Recommend_Header_View *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Recommend_Header" forIndexPath:indexPath];
            header.headerView.image = [UIImage imageNamed:@"推荐菜例1"];
            return header;
        }
    }
    return nil;
}

// 每个cell 中item大小
// 每个cell 中item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    {
        if (indexPath.section == 0) {
            return CGSizeMake(self.view.frame.size.width - 20, self.height);
        } if (indexPath.section == 1) {
            return CGSizeMake(ScreenWidth / 2 - 15, 120.0 / 375 *ScreenWidth);
        }
        
        return CGSizeMake(0, 0);
    }
}

// 每个头部大小
- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if(section == 0) {
        return CGSizeMake(ScreenWidth - 20, 200.0 / 375 *  ScreenWidth);
    }
    
    if (section == 1) {
        return CGSizeMake(self.view.frame.size.width, 40);
    }
    return CGSizeMake(0, 0);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    //    layout.sectionInset = UIEdgeInsetsMake(10, 0, 10, 0);
    if (section == 0) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    } if (section == 1) {
        return UIEdgeInsetsMake(10, 0, 0, 0);
    }
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else {
        return self.recommendArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        Adventure_Detail_Lable_Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"label" forIndexPath:indexPath];
        AdventureDetailModel *model = self.detailArray[indexPath.item];
        cell.introduce.text = model.content;
        return cell;
    }
    if (indexPath.section == 1) {
        AdventureDetail_CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        AdventureDetail_Recommend_Model *model = self.recommendArray[indexPath.item];
        [cell.recommmendImage sd_setImageWithURL:[NSURL URLWithString:model.imagePathThumbnails]];
        cell.name.text = model.name;
        return cell;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        HomePage_display_Controller *display = [[HomePage_display_Controller alloc] init];
        AdventureDetail_Recommend_Model *model = self.recommendArray[indexPath.item];
        display.classid = model.vegetable_id;
        display.classTitle = model.name;
        display.MVBackGroundimage = model.imagePathThumbnails;
        [self.navigationController pushViewController:display animated:YES];
    }
}

- (void)collection:(UIButton *)button
{
    //![adventureModel.freshId compare:@""]
    
    SQL_DataBase *dbManager = [SQL_DataBase shareInstance];
    [dbManager openDB];
    [dbManager creatTable2];
    if (button.selected == NO) {
        button.selected = !button.selected;
        AdventureModel *model = [[AdventureModel alloc] init];
        model.freshId = self.freshid;
        model.name = self.string;
        model.content = self.content;
        model.titleImageFile = self.titleImageFile;
        [dbManager insertActivity:model];
        UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:nil  otherButtonTitles:@"确定", nil];
        [alterView show];
        [alterView release];
    } else
    {
        UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您已收藏" delegate:self cancelButtonTitle:nil  otherButtonTitles:@"确定", nil];
        [alterView show];
        [alterView release];
    }
}

- (void)share
{
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"taiyang" ofType:@"png"];
    
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:self.navigationItem.title
                                       defaultContent:self.navigationItem.title
                                                image:[ShareSDK imageWithPath:imagePath]
                                                title:@"食尚厨房"
                                                  url:@"#"
                                          description:self.navigationItem.title
                                            mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
//    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                }
                            }];
}

- (void)change:(UIButton *)button
{
    button.selected = !button.selected;
    
    if (button.selected == NO) {
        self.height = 135 / 320.0 *ScreenWidth;
        self.openButton.frame = CGRectMake(305.0 / 375 *ScreenWidth, 180 / 375.0 *ScreenWidth + self.height , 45, 20);
        [self.recommendView setContentOffset:CGPointMake(- 10, - 74)];
    }
    if (button.selected == YES) {
        AdventureDetailModel *model = self.detailArray.lastObject;
        
        self.height = [GetHeight hight:model.content wide:ScreenWidth - 20] + 3;
        NSLog(@"%lf", self.height);
        self.openButton.frame = CGRectMake(305.0 / 375 *ScreenWidth, 180 / 375.0 *ScreenWidth + self.height, 45, 20);
    };
    
    [self.recommendView reloadData];
    
}

+ (CGFloat) heightwithText:(NSString *) text
{
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    CGSize size = CGSizeMake((375 - 20) / 375.0 *ScreenWidth, 20000);
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
